import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int ret = solution.threeSumClosest(new int[]{0,0,0}, 1);
        System.out.println(ret);
    }
}


class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);

        int closest = nums[0] + nums[1] + nums[2];
        for(int i = 0; i < nums.length - 2; i++){
            if(i > 0 && nums[i] == nums[i - 1]) continue;
            int a = nums[i];

            int k = nums.length - 1;
            for(int j = i + 1; j < nums.length - 1; j++){
                if(j > i + 1 && nums[j] == nums[j] - 1) continue;
                int b = nums[j];

                int sum = a + b + nums[k];
                while(j < k && sum > target){
                    if(Math.abs(sum - target) < Math.abs(closest - target)){
                        closest = sum;
                    }
                    k--;
                    sum = a + b + nums[k];
                }
                if(j == k) break;
                if(Math.abs(sum - target) < Math.abs(closest - target)){
                    closest = sum;
                }
            }
        }
        return closest;
    }
}